import React from 'react'
import { renderToString } from 'react-dom/server'
import { Route, Routes, matchPath } from 'react-router-dom';
import { StaticRouter } from 'react-router-dom/server';// StaticRouter在服务端使用
import { Provider } from 'react-redux';

import Routers from '../routers.js'
import Header from '../containers/Header'
import { getServerStore } from '../store';

export default function render(req, res) {
  let store = getServerStore();
  let matchedRoutes = Routers.filter((route) => {
    return matchPath(req.path, route.path); // 当前路径和路由配置项匹配，返回boolean值
  });

  let promises = []
  matchedRoutes.forEach((route) => {
    if (!!route.loadData) {
      promises.push(route.loadData(store))
    }
  })
  console.log('ll', promises);
  // 全部执行完后渲染
  Promise.all(promises).then(function () {
    /**
   * renderToString把Home组件转成字符串
   * 由于<Home />是jsx，浏览器不能识别，因此需要转译（webpack）
   * 转译后react.createElement(),因此需要引入react（import React from 'react'）
   * context可以组件进行通信
   */
    let html = renderToString(
      <Provider store={store}>
        <StaticRouter context={{ name: 'lac' }} location={req.path}>
          <>
            <Header />
            <div className="container" style={{ marginTop: 50 }}>
              <Routes>
                {Routers.map(route => (
                  <Route {...route} />
                ))}
              </Routes>
            </div>
          </>
        </StaticRouter>
      </Provider>
    )
    res.send(`
    <!DOCTYPE html>
      <html lang="en">
        <head>
          <meta charset="UTF-8">
          <meta name="viewport" content="width=device-width, initial-scale=1.0">
          <meta http-equiv="X-UA-Compatible" content="ie=edge">
          <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css" >
          <title>react ssr demo</title>
        </head>
        <body>
            <div id="root">${html}</div>
        </body>
        <script>
        window.context = {
            state:${JSON.stringify(store.getState())}
        }
      </script>
        <script src="/index.js"></script>
      </html>
      `);
  })
}